package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;
import biz.util.IdUtil;

import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.Department;
import com.rfid.project.model.Position;
import com.rfid.project.model.Project;
import com.rfid.project.model.ProjectTaskType;
import com.rfid.project.model.ProjectTaskPerson;
import com.rfid.project.model.TechnicalTitle;
import com.rfid.project.service.DepartmentService;
import com.rfid.project.service.PositionService;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectFinishApplyService;
import com.rfid.project.service.ProjectMemberService;
import com.rfid.project.service.ProjectService;
import com.rfid.project.service.ProjectTaskTypeService;
import com.rfid.project.service.ProjectTaskPersonService;
import com.rfid.project.service.TechnicalTitleService;
import com.rfid.project.model.ProjectTask;
import com.rfid.project.service.ProjectTaskService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.util.DateUtil;

@Controller
public class ProjectTaskPersonController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectTaskPersonController.class);

	@Autowired
	private ProjectTaskPersonService projectTaskPersonService;

	@Autowired
	private ProjectTaskService projectTaskService;

	@Autowired
	private PeopleService peopleService;
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private ProjectTaskTypeService projectTaskTypeService;
	
	@Autowired
	private DepartmentService departmentService;
	
	@Autowired
	private PositionService positionService;
	
	@Autowired
	private TechnicalTitleService technicalTitleService;

	@Autowired
	private ProjectMemberService projectMemberService;

	@Autowired
	private ProjectFinishApplyService projectFinishApplyService;
	
	@RequestMapping(value = "/myProjectTaskDetail")
	public String myProjectTaskDetail(HttpServletRequest request,
			HttpServletResponse response, Model model,
			@RequestParam(value = "id", defaultValue = "-1") Long id){
		if(IdUtil.isNotEmpty(id)){
			ProjectTaskPerson projectTaskPerson = this.projectTaskPersonService.findOne(id);
			projectTaskPerson.setStatus(ProcessStatus.processStatusName(projectTaskPerson.getStatus()));
			model.addAttribute("projectTaskPerson", projectTaskPerson);
		}
		return "myProjectTaskDetail";
	}
	
	@RequestMapping(value = "/myProjectTaskmgr")
	public String myProjectTaskmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		
		Set<Project> projects = this.projectMemberService.findAllProjectByPeople(currentUser);
		model.addAttribute("projects", projects);

		List<ProjectTaskType> projectTaskTypes = projectTaskTypeService.findAll();
		model.addAttribute("projectTaskTypes", projectTaskTypes);
		return "myProjectTaskmgr";
	}

	@RequestMapping(value = "/projetTaskPersonmgr")
	public String projetTaskPersonmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		List<ProjectTask> projectTasks = projectTaskService.findAll();
		model.addAttribute("projectTasks", projectTasks);

		List<People> peoples = peopleService.findAll();
		model.addAttribute("peoples", peoples);
		return "projetTaskPersonmgr";
	}
	
	@RequestMapping(value = "/peopleTaskSearch")
	public String peopleTaskSearch(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<Position> positions = positionService.findAll();
		model.addAttribute("positions", positions);

		List<TechnicalTitle> technicalTitles = technicalTitleService.findAll();
		model.addAttribute("technicalTitles", technicalTitles);
		return "peopleTaskSearch";
	}

	@RequestMapping(value = "/lookPeopleTaskDetail")
	public String lookPeopleTaskDetail(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		People people = this.peopleService.findOne(id);
		model.addAttribute("people", people);
		
		Set<Project> projects = this.projectMemberService.findAllProjectByPeople(people);
		model.addAttribute("projects", projects);

		List<ProjectTaskType> projectTaskTypes = projectTaskTypeService.findAll();
		model.addAttribute("projectTaskTypes", projectTaskTypes);
		
		return "peopleTaskDetail";
	}
	
	@RequestMapping(value = "/queryProjectTaskPerson")
	public String queryProjectTaskPerson(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "projectTaskId", defaultValue = "-1") Long projectTaskId,
			@RequestParam(value = "projectTaskTypeId", defaultValue = "-1") Long projectTaskTypeId,
			@RequestParam(value = "peopleId", defaultValue = "-1") Long peopleId,
			@RequestParam(value = "chargePersonSign", defaultValue = "") String chargePersonSign,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "duty", defaultValue = "") String duty,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectTaskPerson> projetTaskPersons = projectTaskPersonService
				.findAll(projectId, projectTaskTypeId, projectTaskId, peopleId, status, chargePersonSign, duty,
						pageNumber, pageSize, sort, order);
		outData(response, projetTaskPersons);
		return null;
	}
	
	@RequestMapping(value = "/queryMiltStatusProjetTasks")
	public String queryMiltStatusProjetTasks(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "projectTaskId", defaultValue = "-1") Long projectTaskId,
			@RequestParam(value = "projectTaskTypeId", defaultValue = "-1") Long projectTaskTypeId,
			@RequestParam(value = "peopleId", defaultValue = "-1") Long peopleId,
			@RequestParam(value = "chargePersonSign", defaultValue = "") String chargePersonSign,
			@RequestParam(value = "status", defaultValue = "") String[] statuses,
			@RequestParam(value = "duty", defaultValue = "") String duty,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectTaskPerson> projetTaskPersons = projectTaskPersonService
				.findAll(projectId, projectTaskTypeId, projectTaskId, peopleId, statuses, chargePersonSign, duty,
						pageNumber, pageSize, sort, order);
		outData(response, projetTaskPersons);
		return null;
	}
	
	@RequestMapping(value = "/findProjectTaskPerson")
	public String findProjectTaskPerson(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectTaskPerson projetTaskPerson = projectTaskPersonService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(projetTaskPerson, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/queryMyProjectTask")
	public String queryMyProjectTask(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "projectTaskId", defaultValue = "-1") Long projectTaskId,
			@RequestParam(value = "projectTaskTypeId", defaultValue = "-1") Long projectTaskTypeId,
			@RequestParam(value = "peopleId", defaultValue = "-1") Long peopleId,
			@RequestParam(value = "chargePersonSign", defaultValue = "") String chargePersonSign,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "duty", defaultValue = "") String duty,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectTaskPerson> projetTaskPersons = projectTaskPersonService
				.findAll(projectId, projectTaskTypeId, projectTaskId, peopleId, status, chargePersonSign, 
				duty, pageNumber, pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", projetTaskPersons.getTotalElements());
		JSONArray models = new JSONArray();
		ProjectTaskPerson temp = new ProjectTaskPerson();
		for (ProjectTaskPerson projetTaskPerson : projetTaskPersons) {
			JSONObject mod = new JSONObject();
			mod.put("id", projetTaskPerson.getId());
			mod.put("chargePersonSign", projetTaskPerson.getChargePersonSign());
			mod.put("status", ProcessStatus.processStatusName(projetTaskPerson.getStatus()));
			mod.put("statusCode", projetTaskPerson.getStatus());
			mod.put("duty", projetTaskPerson.getDuty());
			mod.put("firstPlanFinishDate", DateUtil.dateTheDayToString(projetTaskPerson.getFirstPlanFinishDate()));
			mod.put("planFinishDate", DateUtil.dateTheDayToString(projetTaskPerson.getPlanFinishDate()));
			mod.put("actualFinishDate", DateUtil.dateTheDayToString(projetTaskPerson.getActualFinishDate()));
			mod.put("planWorktime", projetTaskPerson.getPlanWorktime());
			
			People chargePersonSignPerson = null;
			if("Y".equals(projetTaskPerson.getChargePersonSign())){
				chargePersonSignPerson = projetTaskPerson.getPeople();
			}else{
				temp.setProjectTask(projetTaskPerson.getProjectTask());
				temp.setChargePersonSign("Y");
				
				ProjectTaskPerson ptp = this.projectTaskPersonService.findProjetTaskPerson(temp);
				if(null != ptp){
					chargePersonSignPerson = ptp.getPeople();
				}
			}
			String chargePersonSignPersonName = "[暂无]";
			if(null != chargePersonSignPerson){
				chargePersonSignPersonName = chargePersonSignPerson.getName();
			}
			mod.put("chargePersonSignPersonName", chargePersonSignPersonName);
			
			ProjectTask projectTask = projetTaskPerson.getProjectTask();
			mod.put("projectName", projectTask.getProject().getName());
			mod.put("taskDescription", projectTask.getTaskDescription());
			mod.put("projectTaskTypeName", projectTask.getProjectTaskType().getName());
			mod.put("projectTaskTaskDescription", projectTask.getTaskDescription());
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}

	//输出数据
	private void outData(HttpServletResponse response,
			Page<ProjectTaskPerson> projetTaskPersons) {
		JSONObject object = new JSONObject();
		object.put("total", projetTaskPersons.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectTaskPerson item : projetTaskPersons) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		
		PageJsonBean.printObject(response, object);
	}

	private void wrapData(ProjectTaskPerson item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("originalConsumeWorktime", item.getOriginalConsumeWorktime());
		mod.put("confirmConsumeWorktime", item.getConfirmConsumeWorktime());
		mod.put("duty", item.getDuty());
		mod.put("chargePersonSign", item.getChargePersonSign());
		mod.put("peopleId", item.getPeople().getId());
		mod.put("peopleName", item.getPeople().getName());
		
		mod.put("taskCreateTime", DateUtil.dateTheDayToString(item.getTaskCreateTime()));
		mod.put("taskPublishTime", DateUtil.dateTheDayToString(item.getTaskPublishTime()));
		mod.put("taskBeginDate", DateUtil.dateTheDayToString(item.getTaskBeginDate()));
		mod.put("taskAcceptTime", DateUtil.dateTheDayToString(item.getTaskAcceptTime()));
		mod.put("firstPlanFinishDate", DateUtil.dateTheDayToString(item.getFirstPlanFinishDate()));
		mod.put("planFinishDate", DateUtil.dateTheDayToString(item.getPlanFinishDate()));
		mod.put("actualFinishDate", DateUtil.dateTheDayToString(item.getActualFinishDate()));
		mod.put("planWorktime", item.getPlanWorktime());
		mod.put("planFinishDateChangeCount", item.getPlanFinishDateChangeCount());

		ProjectTask projectTask = item.getProjectTask();
		mod.put("projectTaskId", projectTask.getId());
		mod.put("projectTaskTaskDescription", projectTask.getTaskDescription());
		mod.put("projectId", projectTask.getProject().getId());
		mod.put("projectName", projectTask.getProject().getName());
		mod.put("taskCreatorId", projectTask.getTaskCreator().getId());
		mod.put("taskCreatorName", projectTask.getTaskCreator().getName());
		mod.put("projectTaskTypeId", projectTask.getProjectTaskType().getId());
		mod.put("projectTaskTypeName", projectTask.getProjectTaskType().getName());
		mod.put("taskDescription", projectTask.getTaskDescription());
		mod.put("planSumWorktime", projectTask.getPlanWorktime());
		mod.put("projectTaskActualFinishDate", DateUtil.dateTheDayToString(projectTask.getActualFinishDate()));
		
		Float ctualWorktime = projectTask.getActualWorktime();
		mod.put("actualWorktime", ctualWorktime == null?0:ctualWorktime);
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
		mod.put("statusCode", item.getStatus());
	}
	
	@RequestMapping(value = "/editProjetTaskPerson", method = RequestMethod.POST)
	public String editProjetTaskPerson(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTaskPerson projetTaskPerson,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectTaskPersonService.saveProjetTaskPerson(projetTaskPerson);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectTaskPerson")
	public String delProjectTaskPerson(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectTaskPersonService.deleteProjetTaskPerson(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/acceptProjectTaskPerson")
	public String acceptProjectTaskPerson(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTaskPerson projetTaskPerson,
			Model model, RedirectAttributes redirectAttributes) {
		this.projectTaskPersonService.acceptProjectTaskPerson(projetTaskPerson);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/revocationDelayApplyProjectTaskPerson")
	public String revocationDelayApplyProjectTaskPerson(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTaskPerson projectTaskPerson,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectTaskPersonService.revocationDelayApplyProjectTaskPerson(projectTaskPerson);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	@RequestMapping(value = "/revocationFinishApplyProjectTaskPerson")
	public String revocationFinishApplyProjectTaskPerson(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTaskPerson projectTaskFinishPerson,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectTaskPersonService.revocationFinishApplyProjectTaskPerson(projectTaskFinishPerson);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
